import { spawn } from 'child_process'
import { Context } from './types'

/**
 * Execute `npm | yarn | pnpm install` command.
 */
export default async (ctx: Context): Promise<void> => {
  // 判断是否关闭install
  if (ctx.config.install === false) return // off install

  // install没有设置
  if (ctx.config.install == null) {
    // not contains `package.json`
    // 查看是否有package.json文件 没有则install
    if (ctx.files.find(i => i.path === 'package.json') == null) return
    // npm is used by default when it contains `package.json`
    ctx.config.install = 'npm'
  }

  // Installing dependencies...

  // 根据客户端模块安装
  const client = ctx.config.install
  /* istanbul ignore next */
  const cmd = process.platform === 'win32' ? client + '.cmd' : client

  // 启用一个子进程
  await new Promise((resolve, reject) => {
    // 执行命令 io流进程中打印的东西同时显示到客户端中
    const child = spawn(cmd, ['install'], { cwd: ctx.dest, stdio: 'inherit' })
    child.on('error', reject).on('exit', code => {
      if (code === 0) return resolve()
      reject(new Error('Install dependencies failed.'))
    })
  })

  // Install deps completed。
}
